package batch.ecircle;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.*;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.*;
import java.io.*;
import java.util.Date;
import java.security.*;

public class makeProductUserFile
{
    final String TODAY = DateFormatUtils.format(new Date(), "yyyyMMdd");

    String strCountry = "";     //Which Country
    String strSplit   = "";     //Separate file or Not
    String strFileGB  = "";

    public makeProductUserFile(String strPrCountry, String strPrSplit) {
        strCountry = (strPrCountry.equals("all")) ? "" : StringUtils.defaultString(strPrCountry);
        strSplit   = StringUtils.defaultString(strPrSplit);
    }

    public static void main(String [] args) {
        Logger.getLogger("ecircle.makeProductUserFile").info("( * ) Start.");

        makeProductUserFile mkUser = null;

        if( args.length == 2 ){
            mkUser = new makeProductUserFile(args[0], args[1]);
        }
        else{
            System.exit(-1);
        }

        mkUser.startMake();

        Logger.getLogger("ecircle.makeProductUserFile").info("( * ) End.");
    }

    //Make a log file and a data file.
    public void startMake(){
        Connection   conn = null;
        Statement    stmt = null;
        ResultSet    rs   = null;
        OutputStreamWriter oswFile = null;

        String fileNm  = "/home01/sfc/batch/ecircle/data/all_" + strCountry + "_product" + TODAY + ".txt";

        int cnt = 0;
        int rsCnt = 0;

        String sUserNo = "";
        String sMD5 = "";

        StringBuffer sbTemp = new StringBuffer();

        StringBuffer sQuery = new StringBuffer()
                             .append("SELECT A.USER_NO                                \n")
                             .append("     , A.ID                                     \n")
                             .append("     , DECODE(A.FIRSTNAME, 'WAP_TEMP', 'member' \n")
                             .append("                         , 'SIM_TEMP', 'member' \n")
                             .append("                         , ''        , 'member' \n")
                             .append("                         , NULL      , 'member' \n")
                             .append("                         , A.FIRSTNAME)         \n")
                             .append("     , A.LASTNAME                               \n")
                             .append("     , A.GENDER                                 \n")
                             .append("     , A.BIRTH                                  \n")
                             .append("     , A.HP_BRAND                               \n")
                             .append("     , REPLACE(A.HP_MODEL, 'SGH-', '')          \n")
                             .append("     , A.HP_BUY_YM                              \n")
                             .append("     , A.MEMBERGBN                              \n")
                             .append("     , A.EMAIL                                  \n")
                             .append("     , A.HP_PROVIDER                            \n")
                             .append("     , A.INCOME                                 \n")
                             .append("     , A.POSTCODE                               \n")
                             .append("  FROM G_MB_MEMBER A                            \n")
                             .append("     , G_MB_OPTIN  B                            \n")
                             .append(" WHERE A.USER_NO      =  B.USER_NO              \n")
                             .append("   AND A.REG_COUNTRY  =  '" + strCountry + "'   \n")
                             .append("   AND A.DELETED      IS NULL                   \n")
                             .append("   AND B.CODE         =  '0113003'              \n");

        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            conn = DriverManager.getConnection("jdbc:oracle:thin:@eu-anydb:1521:ORAEU", "gsms", "any02gs");
            conn.setAutoCommit(true);
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sQuery.toString());
			rsCnt = rs.getMetaData().getColumnCount();

            oswFile = new OutputStreamWriter(new FileOutputStream(fileNm, false), "ISO-8859-1");

            MessageDigest md5 = MessageDigest.getInstance("MD5");

            while(rs.next()){
				sbTemp.setLength(0);

                for(int i=1;i<=rsCnt;i++) {
                    sbTemp.append(ObjectUtils.toString(rs.getObject(i), ""));

                    if( i == rsCnt ){
                        sbTemp.append("\n");
                    }
                    else{
                        sbTemp.append("|");

                        if(i == 1){
                            sUserNo = ObjectUtils.toString(rs.getObject(i), "");

                            md5.reset();
                            md5.update(("abc" + sUserNo + "xyz").getBytes());

                            sMD5 = this.bytesToHex(md5.digest());

                            sbTemp.append(sMD5 + StringUtils.leftPad(sUserNo, 10, '0') + "|");  //For auto login

                            sbTemp.append(sMD5 + "|");  //For opt-out
                        }
                    }
                }

                oswFile.write(sbTemp.toString());
                cnt++;

                if(cnt % 500 == 0){
                    Logger.getLogger("ecircle.makeProductUserFile").info("here we are == " + cnt);
                }
            }

            Logger.getLogger("ecircle.makeProductUserFile").info("Total Count : " + cnt);
        }
        catch(Exception ex) {
            ex.printStackTrace();

            Logger.getLogger("ecircle.makeProductUserFile").info(ex.toString());
            StackTraceElement[] stElement = ex.getStackTrace();
            for(int p=0; p<stElement.length;p++){
                Logger.getLogger("ecircle.makeProductUserFile").info(stElement[p].toString());
            }
        }
        finally {
            if (rs   != null) try { rs.close(); }   catch (Exception e) { e.printStackTrace(); }
            if (stmt != null) try { stmt.close(); } catch (Exception e) { e.printStackTrace(); }
            if (conn != null) try { conn.close(); } catch (Exception e) { e.printStackTrace(); }
            if (oswFile != null) try { oswFile.close(); } catch (Exception e) { e.printStackTrace(); }
        }
    }

    private String bytesToHex(byte[] b) {
        char hexDigit[] = {
			'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
			'a', 'b', 'c', 'd', 'e', 'f'
		};

		StringBuffer buf = new StringBuffer();
		for (int i=0 ; i<b.length ; i++) {
		    buf.append(hexDigit[b[i] >> 4 & 0xf]);
		    buf.append(hexDigit[b[i] & 0xf]);
		}

		return buf.toString();
    }
}
